/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pb138.videodes.impl;

import cz.muni.fi.pb138.videodes.api.exceptions.ExistConnectionException;
import cz.muni.fi.pb138.videodes.api.base.XMLDBDriver;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.exist.storage.DBBroker;
import org.exist.xmldb.DatabaseInstanceManager;
import org.exist.xmldb.XQueryService;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.CollectionManagementService;

/**
 *
 * @author pseudo
 */
public class VideoDesDriver implements XMLDBDriver {
    private static final String URI = "xmldb:exist://";
    private static final String DRIVER = "org.exist.xmldb.DatabaseImpl";
     
    private static final Logger LOGGER = Logger.getLogger(XMLDBDriver.class.getName());
    
    
    
    @Override
    public void open(){
	try {
	    Class cl = Class.forName(DRIVER);
	    
	    Database db =(Database) cl.newInstance();
	    db.setProperty("create-database", "true");
	    db.setProperty("configuration", "conf.xml");
	    
	    DatabaseManager.registerDatabase(db);	
	    
	    this.initDb();
	} catch (Exception ex) {
	    LOGGER.log(Level.SEVERE, "An error occurred while connecting to the database", ex);
	    throw new ExistConnectionException(ex.getMessage());
	}    
    }
    
    @Override
    public void close(){
	try {
	    Collection root = DatabaseManager.getCollection(URI + DBBroker.ROOT_COLLECTION, "admin", "" );
	    DatabaseInstanceManager manager = (DatabaseInstanceManager) root.getService("DatabaseInstanceManager", "1.0");
	    manager.shutdown();
	} catch (XMLDBException ex) {
	    LOGGER.log(Level.SEVERE, "Error when closing DB connection (database shutdown).", ex);
	    throw new ExistConnectionException(ex.getMessage());
	}	
    }
    
    @Override
    public XQueryService getService() {
	XQueryService service = null;	    
	Collection col = null;
	try {
	    col = DatabaseManager.getCollection(URI + DBBroker.ROOT_COLLECTION, "admin", "" );
	    service = (XQueryService) col.getService("XQueryService", "1.0");
	} catch (XMLDBException ex) {
	    LOGGER.log(Level.SEVERE, "An error occurred while retreaving XQuery Service", ex);
	}
	return service;
    }
    
    @Override
    public  Collection getCollection(String name) throws XMLDBException{		
	Collection col = DatabaseManager.getCollection(URI + DBBroker.ROOT_COLLECTION + name, "admin", "");
	return col;
    }
    
    private void initDb() throws XMLDBException{
	Collection root = DatabaseManager.getCollection(URI + DBBroker.ROOT_COLLECTION, "admin", "");

        CollectionManagementService cms = (CollectionManagementService) root.getService("CollectionManagementService", "1.0");
        cms.createCollection("/dvd");
        cms.createCollection("/movie");
    }
    
}